<template>
  <div class="container">
    <div class="app-container">
      <!-- 按钮 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 表格组件 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <!-- active-value = '开启条件' inactive-value = '未开启条件' -->
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button size="mini" type="primary" @click="confirmEdit(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="确定删除该条数据吗？" @onConfirm="delRole(row.id)">
                <el-button slot="reference" style="margin-left: 10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination :page-size="pageParams.pagesize" :current-page="pageParams.page" :total="pageParams.total" layout="prev, pager, next" @current-change="ChangePage" />
      </el-row>
    </div>
    <!-- 弹层组件 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="close">
      <!-- 表单内容 -->
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="form.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="form.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini">确定</el-button>
              <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
      <el-tree :data="depts" ref="permTree" node-key="id" :default-checked-keys="permIds" :props="defaultProps" default-expand-all show-checkbox />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, editRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { listToTree } from '@/utils/index'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      tableData: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      form: {
        name: '',
        state: 1,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false,
      showPermissionDialog: false,
      depts: [],
      permIds: [],
      currentRoleId: null
    }
  },
  // computed: {
  //   state() {
  //     return this.tableData.state === 1 ? '启用' : '未启用'
  //   }
  // },
  created() {
    this.getTableData()
  },
  methods: {
    // 确定编辑
    async btnOK() {
      await assignPerm({
        roleId: this.currentRoleId,
        // 树组件的选中没有响应式，需要通过树组件中的getCheckedKeys方法获取选中项的key
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    // 分配权限
    async btnPermission(id) {
      // 赋值id
      this.currentRoleId = id
      // 获取角色已有权限id
      const { permIds } = await getRoleDetail(id)
      // 赋值
      this.permIds = permIds
      // 获取权限点列表转为树形并赋值(先选中已有权限，再显示权限点列表，可以避免重复选择的bug)
      this.depts = listToTree(await getPermissionList(), 0)
      // 显示弹层
      this.showPermissionDialog = true
    },
    // 获取角色数据
    async getTableData() {
      const { rows, total } = await getRoleList(this.pageParams)
      // console.log('获取角色', rows)
      this.tableData = rows
      this.pageParams.total = total
      // 针对每个数据进行标记
      this.tableData.forEach(item => {
      // item.isEdit = false // 添加一个属性 初始值为flase
      // 数据响应式的问题 数据变化 视图更新
      // 添加动态属性 不具备响应式特点
      // this.$set(目标对象,属性名称,初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        // 添加一个缓存数据，利用缓存属性来修改值
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 改变页码
    ChangePage(page) {
      this.pageParams.page = page
      this.getTableData()
    },
    // 确认按钮
    async confirm() {
      // 1.验证表单
      this.$refs.form.validate()
      // 2.调用接口
      await addRole(this.form)
      // 3.提示用户
      this.$message.success('新增角色成功')
      // 4.重置表单+关闭弹层
      this.close()
    },
    close() {
      // 清除表单数据
      this.$refs.form.resetFields()
      // 关闭弹层
      this.showDialog = false
    },
    // 点击编辑行
    btnEditRow(row) {
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
      row.isEdit = true // 改变行的编辑状态
    },
    // 确认编辑
    async confirmEdit(row) {
      // 判断输入内容是否为空
      if (row.editRow.name && row.editRow.description) {
        // 发送请求
        await editRole({ ...row.editRow, id: row.id })
        // 提示用户
        this.$message.success('修改角色成功')
        // 退出编辑状态并更新页面数据
        // 以下提示错误是eslint的误判(可以通过摸出错误提示，点击快速修复，点击第一个英文修复)
        // row.isEdit = false
        // row.name = row.editRow.name
        // row.state = row.editRow.state
        // row.description = row.editRow.description
        // 也可以通过浅拷贝
        // Object.assign() 浅拷贝 - 克隆 / 合并
        // Object.assign() 将一个或多个源对象中的属性值复制到目标对象中
        // Object.assign(目标对象, 源对象1,源对象2,...)
        Object.assign(row, { ...row.editRow, isEdit: false })
      } else {
        this.$message.error('角色名称和描述不能为空')
      }
    },
    async delRole(id) {
      await delRole(id)
      // 判断是不是最后一条角色数据 是 删除后返回前一页
      if (this.tableData.length === 1) {
        this.pageParams.page--
      }
      this.getTableData()
    }
  }
}
</script>

<style lang="scss" scoped>
.role-operate{
  padding: 10px;
}
</style>
